/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Control;

import entities.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.aptech.session.beans.EventFacade;
import org.aptech.session.beans.PrizeFacade;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import utils.Constants;
import utils.SumaryPrize;
import utils.WinnerDetails;

/**
 *
 * @author Chien
 */
@ManagedBean
@SessionScoped
public class EventControl implements Serializable {

    @EJB
    private PrizeFacade prizeFacade;
    @EJB
    private EventFacade eventFacade;
    private Event selectedevent;
    private Event newEvent = new Event();
    /**
     * upcoming event: event's starting date is greater than current date.
     */
    /**
     * current event: event's starting date is less than current date and
     * event's ending date is not greater than current date
     */
    private List<Event> events;
    private final int SHORT_DESCRIPTION_LENGHT = 150;
    private final int MEDIUM_DESCRIPTION_LENGHT = 500;
    private String uploadFileName = " ";

    public List<SumaryPrize> selectAllPrizeByEvent() {
        ArrayList<SumaryPrize> sumaryPrizesList = new ArrayList<SumaryPrize>();
        Event event = selectedevent;
        if (null == event) {
            System.out.println("---selectAllPrizeByEvent: event is NULL-----");
            return sumaryPrizesList;
        }
        SumaryPrize sumaryPrize = new SumaryPrize(event);
        // get list<prize> within a month.
        List<Prize> prizeList = event.getPrizeList();
        try {
            // get Registration from prize
            for (Prize prize : prizeList) {

                List<Winner> winnerList = prize.getWinnerList();
                for (Winner winner : winnerList) {
                    Registration registration = winner.getRegId();
                    // find User by registration
                    User user = registration.getUserName();
                    // create new WinnerDetails
                    WinnerDetails winnerDetails = new WinnerDetails(user, prize);
                    //create new SumaryPrize

                    // add WinnerDetails into sumaryPrizesList list
                    sumaryPrize.getWinnerList().add(winnerDetails);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sumaryPrizesList;
    }

    public void redirectToEvent(Event event) {

        System.out.println("------redirectToEvent------------------");
        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/userWeb/events_details.xhtml";
        utils.Uility.redirectPage(context, event, path);
    }

//    public List<Prize> getAllPrizeByEvent() {
//        if (null != selectedevent) {
//            return selectedevent.getPrizeList();
//        } else {
//            return new ArrayList<Prize>();
//
//        }
//    }
    /**
     * Make short description of event
     *
     * @param event
     * @return string of short description of event
     */
    public String shortEventDescription(Event event) {
        String shortDes = event.getDescription();
        if (null != shortDes) {
            if (shortDes.length() > SHORT_DESCRIPTION_LENGHT) {
                shortDes = shortDes.substring(0, SHORT_DESCRIPTION_LENGHT) + "...";
            }
        }
        return shortDes;
    }

    public String mediumEventDescription(Event event) {
        String shortDes = event.getDescription();
        if (null != shortDes) {
            if (shortDes.length() > MEDIUM_DESCRIPTION_LENGHT) {
                shortDes = shortDes.substring(0, MEDIUM_DESCRIPTION_LENGHT) + "...";
            }
        }
        return shortDes;
    }

    /**
     * current event: event's starting date is less than current date and
     * event's ending date is not greater than current date
     *
     * @return List<Event>
     */
    public List<Event> getCurrentEventList() {
        return eventFacade.getCurrentEvents();
    }

    public List<Event> pastEvents() {
        return eventFacade.getPastEvents();
    }

    /**
     * upcoming event: event's starting date is greater than current date.
     *
     * @return List<Event>
     */
    public List<Event> getUpcomingEventList() {
        return eventFacade.getUpcomingEvents();
    }

    public Event getSelectedevent() {
        return selectedevent;
    }

    public void setSelectedevent(Event selectedevent) {
        this.selectedevent = selectedevent;
    }

    public Event getNewEvent() {
        return newEvent;
    }

    public void setNewEvent(Event newEvent) {
        this.newEvent = newEvent;
    }

    /**
     * Creates a new instance of EventControl
     */
    public EventControl() {
        selectedevent = new Event();

    }

    public List<Event> getAllEvent() {
        events = eventFacade.findAll();
        return events;
    }

    public List<Event> getAllActiveEvents() {
        return eventFacade.getAllActiveEvents();
    }

    public void handleFileUploadAddEvent(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg
                    uploadFileName = Constants.DATABASE_IMAGE_PATH + time + ext;
                    newEvent.setPhoto(uploadFileName);
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + uploadFileName);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }


    }

    public void handleFileUploadEditEvent(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg
                    uploadFileName = Constants.DATABASE_IMAGE_PATH + time + ext;
                    selectedevent.setPhoto(uploadFileName);
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + uploadFileName);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }


    }

    public void insert() {
        try {

            eventFacade.create(newEvent);
            newEvent = new Event();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create Success", ""));
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventManager.xhtml");
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Insert failed", ""));
        }

    }

    public void edit() {
        try {
            eventFacade.edit(selectedevent);
            FacesContext context = FacesContext.getCurrentInstance();

            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventManager.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void delete(Event event) {
        try {
            eventFacade.remove(event);
            FacesContext context = FacesContext.getCurrentInstance();

            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventManager.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void goInsert() {
        try {

            FacesContext context = FacesContext.getCurrentInstance();

            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventInsert.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void showDetail(Object event) {

        selectedevent = (Event) event;
        try {

            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath() + "/faces/Admin/EventUpdate.xhtml");


        } catch (IOException ex) {
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public List<Prize> getPrizeByEventId(String eventid) {
        return prizeFacade.findByEvent(eventid);
    }

    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public void resetForm() {
        selectedevent.setEventId("");
        selectedevent.setTitle("");
        selectedevent.setDescription("");
        selectedevent.setPhoto("");
//        selectedevent.setMinPlayer(Integer.parseInt(""));
//        selectedevent.setMaxPlayer(Integer.parseInt(""));
//        selectedevent.setIsActive(false);
//        selectedevent.setStartRegDate(new Date());
//        selectedevent.setEndRegDate(new Date());
//        selectedevent.setStartDate(new Date());
//        selectedevent.setEndDate(new Date());
    }
}
